import 'dart:io';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

/// 视频缩略图缓存管理器
/// 用于缓存已经初始化的视频控制器，避免重复创建
class VideoThumbnailCache {
  static final VideoThumbnailCache _instance = VideoThumbnailCache._internal();
  factory VideoThumbnailCache() => _instance;
  VideoThumbnailCache._internal();

  // 缓存已初始化的视频控制器
  final Map<String, VideoPlayerController> _controllerCache = {};

  // 缓存正在初始化的Future，避免重复初始化
  final Map<String, Future<VideoPlayerController?>> _initializingCache = {};

  /// 获取或创建视频控制器
  Future<VideoPlayerController?> getOrCreateController(
    String videoPath, {
    Duration? thumbnailTime,
    bool useSmartThumbnail = true,
  }) async {
    // 生成缓存键
    final cacheKey = _generateCacheKey(
      videoPath,
      thumbnailTime,
      useSmartThumbnail,
    );

    // 如果已经有缓存的控制器，直接返回
    if (_controllerCache.containsKey(cacheKey)) {
      final controller = _controllerCache[cacheKey]!;
      if (controller.value.isInitialized) {
        return controller;
      } else {
        // 如果控制器已经被释放，从缓存中移除
        _controllerCache.remove(cacheKey);
      }
    }

    // 如果正在初始化，返回正在进行的Future
    if (_initializingCache.containsKey(cacheKey)) {
      return await _initializingCache[cacheKey];
    }

    // 创建新的初始化Future
    final initializeFuture = _createController(
      videoPath,
      thumbnailTime,
      useSmartThumbnail,
    );
    _initializingCache[cacheKey] = initializeFuture;

    try {
      final controller = await initializeFuture;
      if (controller != null) {
        _controllerCache[cacheKey] = controller;
      }
      return controller;
    } finally {
      // 初始化完成后，从正在初始化的缓存中移除
      _initializingCache.remove(cacheKey);
    }
  }

  /// 创建视频控制器
  Future<VideoPlayerController?> _createController(
    String videoPath,
    Duration? thumbnailTime,
    bool useSmartThumbnail,
  ) async {
    try {
      VideoPlayerController controller;

      // 如果是 assets 路径，使用 VideoPlayerController.asset
      if (videoPath.startsWith('assets/')) {
        controller = VideoPlayerController.asset(videoPath);
      } else {
        if (!File(videoPath).existsSync()) {
          debugPrint('视频文件不存在: $videoPath');
          return null;
        }
        controller = VideoPlayerController.file(File(videoPath));
      }

      await controller.initialize();

      // 确定缩略图时间点
      Duration targetTime;
      final videoDuration = controller.value.duration;

      if (thumbnailTime != null) {
        targetTime = thumbnailTime > videoDuration
            ? videoDuration
            : thumbnailTime;
      } else if (useSmartThumbnail) {
        targetTime = _getSmartThumbnailTime(videoDuration);
        if (targetTime > videoDuration) {
          targetTime = videoDuration;
        }
      } else {
        targetTime = Duration.zero;
      }

      if (targetTime > Duration.zero) {
        await controller.seekTo(targetTime);
      }

      return controller;
    } catch (e) {
      debugPrint('创建视频控制器失败: $e');
      return null;
    }
  }

  /// 生成缓存键
  String _generateCacheKey(
    String videoPath,
    Duration? thumbnailTime,
    bool useSmartThumbnail,
  ) {
    return '$videoPath-${thumbnailTime?.inMilliseconds ?? 'null'}-$useSmartThumbnail';
  }

  /// 智能缩略图时间选择
  Duration _getSmartThumbnailTime(Duration videoDuration) {
    final quarterTime = Duration(
      milliseconds: (videoDuration.inMilliseconds * 0.25).round(),
    );

    // 最小1秒，最大10秒
    if (quarterTime.inSeconds < 1) {
      return const Duration(seconds: 1);
    } else if (quarterTime.inSeconds > 10) {
      return const Duration(seconds: 10);
    } else {
      return quarterTime;
    }
  }

  /// 预加载视频缩略图
  /// 可以在列表滚动时提前加载即将显示的视频
  Future<void> preloadThumbnail(
    String videoPath, {
    Duration? thumbnailTime,
    bool useSmartThumbnail = true,
  }) async {
    // 异步预加载，不阻塞当前操作
    getOrCreateController(
      videoPath,
      thumbnailTime: thumbnailTime,
      useSmartThumbnail: useSmartThumbnail,
    ).catchError((e) {
      debugPrint('预加载视频缩略图失败: $e');
      return null; // 返回 null 以满足类型要求
    });
  }

  /// 清理指定的缓存
  void removeFromCache(
    String videoPath, {
    Duration? thumbnailTime,
    bool useSmartThumbnail = true,
  }) {
    final cacheKey = _generateCacheKey(
      videoPath,
      thumbnailTime,
      useSmartThumbnail,
    );
    final controller = _controllerCache.remove(cacheKey);
    controller?.dispose();
  }

  /// 清理所有缓存
  void clearCache() {
    for (final controller in _controllerCache.values) {
      controller.dispose();
    }
    _controllerCache.clear();
    _initializingCache.clear();
  }

  /// 清理未使用的缓存（可以定期调用）
  void cleanupUnusedCache() {
    final keysToRemove = <String>[];

    for (final entry in _controllerCache.entries) {
      final controller = entry.value;
      if (!controller.value.isInitialized) {
        keysToRemove.add(entry.key);
        controller.dispose();
      }
    }

    for (final key in keysToRemove) {
      _controllerCache.remove(key);
    }
  }

  /// 获取缓存统计信息
  Map<String, int> getCacheStats() {
    return {
      'cached_controllers': _controllerCache.length,
      'initializing_controllers': _initializingCache.length,
    };
  }
}
